var form = layui.form, laydate = layui.laydate, annexList = [],userList = [], upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"),
    status = getQueryVariable("status");
layui.use(['tableEdit',"selectInput"], function () {

    let  tableEdit = layui.tableEdit;
    let layer = layui.layer;
    let selectInput = layui.selectInput;

    //客户信息
    let customerInfo = [];
    //客户联系人
    let customerContact = [];
    //出库人
    let deliverer = [];
    let detailData = [];
    let annexList = [];
    let operationLog = [];


    let tempDetail = [];
    let tempAnnexList = [];

    $(document).ready(function () {
        //1.获取所有下拉框信息
        getSelectData();

        //2.获取详情信息
        getDetailInfo();

        table.reload('storageproductstableid',{data : tempDetail});
        table.reload('attachmenttableid',{data : tempAnnexList});
    });

    function getDetailInfo() {
        //获取详情信息
        $.ajax({
            url:"otherOutStock/detail/update?id="+id,
            async:false,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    setCustomerInfo(res.data.receiptCompanyName);
                    //获取客户联系人
                    getCustomerContactName(res.data.companyCode);
                    $("#receiptCompanyName").val(res.data.receiptCompanyName);
                    $("#companyCode").val(res.data.companyCode);
                    $("#contactPersonAddress").val(res.data.contactPersonAddress);
                    $("#contactPersonPhone").val(res.data.contactPersonPhone);
                    $("#id").val(res.data.id);
                    $("#billNo").val(res.data.billNo);
                    $("#newBillNo").val(res.data.billNo);
                    $("#outStockDate").val(res.data.outStockDate);
                    getOutStockInfo(res.data.delivererCode);
                    $("#outStockPerson").val(res.data.outStockPerson);
                    $("#founder").val(res.data.creator);
                    $("#createDate").val(res.data.createDate);
                    $("#memo").val(res.data.memo);

                    //产品列表信息
                    let detailData = res.data.detailVos;
                    for(let i in detailData){
                        tempDetail.push(detailData[i]);
                    }

                    //附件信息
                    let annexList = res.data.annexVos;
                    for(let i in annexList){
                        tempAnnexList.push(annexList[i]);
                    }

                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    function getSelectData(){
        //获取所有用户信息
        $.ajax({
            url:"otherOutStock/getAllUserInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    deliverer = data.data;
                    for(let i in data.data){
                        $('#delivererCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });
    }



    //获取出库人信息
    function getOutStockInfo(code){
        $.ajax({
            url:"otherOutStock/getAllUserInfo",
            success:function(data){
                if(data.status == 200){
                    for(let i in data.data){
                        $('#delivererCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    $('#delivererCode').val(code);
                    form.render('select');
                }
            }
        });
    }

    function setCustomerInfo(initData) {
        //客户名称
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })
        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#companyCode").val(code);
            $("#receiptCompanyName").val(name);
            //获取客户联系人
            getCustomerContactName(code);
        });
    }

    function getCustomerContactName(customCode) {
        //通过客户编码获取客户联系人
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:customCode,
            url:"otherOutStock/add/getCustomerContactInfo",
            async:false,
            success:function(res){
                if(res.status == 200){
                    customerContact = res.data;
                    //客户联系人重新赋值
                    $("#contactPerson").empty();
                    for(let i in res.data){
                        $('#contactPerson').append(new Option(res.data[i].name, res.data[i].name));
                    }
                    //默认选中第一个
                    if(res.data.length > 0){
                        $('#contactPerson').val(res.data[0].name);
                        $('#contactPersonPhone').val(res.data[0].phone);
                        $('#contactPersonAddress').val(res.data[0].address);
                    }
                    form.render('select');
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    //监听客户联系人下拉框
    form.on("select(contactPerson)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in customerContact){
            if(data.value == customerContact[i].name){
                $('#contactPersonPhone').val(customerContact[i].phone);
                $('#contactPersonAddress').val(customerContact[i].address);
                form.render();
                break;
            }
        }
    });


    //监听出货人
    form.on('select(delivererCode)', function (data) {
        if(data.value === ""){
            $("#outStockPerson").val("");
            return;
        }
        let name = "";
        for(let i in deliverer){
            if(deliverer[i].code = data.value){
                name = deliverer[i].name;
            }
        }
        $("#outStockPerson").val(name);
        form.render('select');
    })

    //表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "outboundorderno": "出库单号",
        })
    }

    //监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        req["status"] = status;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        //获取库存表单信息数据
        let transferDetails = table.cache["storageproductstableid"];
        if(transferDetails.length > 0){
            for(let i in transferDetails){
                if(null == transferDetails[i].outStockQuantity || transferDetails[i].outStockQuantity <= 0){
                    layer.confirm("存在出库数量为零的记录，这些记录审批后不会生成相关记录，是否删除？",
                        confirmInfo(3,6),
                        function (index) {
                            var newData = deleteTransferData(transferDetails);
                            table.reload('storageproductstableid',{data : newData});
                            layer.close(index);
                        });
                    return false;
                }
            }
        }

        req["annexList"] = annexReqs;
        req["details"] = transferDetails;
        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"otherOutStock/add",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/WarehouseManagement/otheroutbound.jsp");
                        parent.intab("views/jsp/WarehouseManagement/otheroutbound.jsp","其它出库")
                        parent.detab("views/jsp/WarehouseManagement/tpl/otherOutStockUpdate.jsp" + (id == '' ? '' : '?id=' + id+"&status="+status));
                        //parent.detab("views/jsp/WarehouseManagement/tpl/otherOutStockUpdate.jsp" + (id == '' ? '' : '?id=' + id));
                    },)
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
        return false;
    });

    //遍历删除调拨数量为0的数据
    function deleteTransferData(transferDetails){
        for(var j = 0; j < transferDetails.length; j++){
            if(transferDetails[j].outStockQuantity <= 0){
                transferDetails.splice(j, 1);
                j--;
            }
        }
        return transferDetails;
    }

//--入库产品信息
    var cols = table.render({
        elem: '#storageproducts',
        data: detailData,
        id: 'storageproductstableid',
        toolbar: '#storageproductstoolbar',
        cols: [[
            //{field: 'productimg', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'productCode', width: 120, title: '产品编码', sort: true},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'lotNo', width: 120, title: '批次号', sort: true},
            {field: 'warehouseName',width: 120,title: '仓库名称'},
            {field: 'productUnit', width: 120, title: '产品单位', sort: true},
            {field: 'outStockQuantity', width: 120, title: '出库数量',event: 'outStockQuantity',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'stockQuantity', width: 120, title: '库存数量'},
            {field: 'costSubtotal', width: 120, title: '成本小计'},
            {field: 'stockCost', width: 120, title: '成本单价'},
            {field: 'shareCostPrice', width: 160, title: '分摊费用单价'},
            {field: 'trayNumber', width: 120, title: '托盘入数', sort: true},
            {field: 'totalTray', width: 120, title: '总托盘', sort: true},
            {field: 'inStoreBillNo', width: 120, title: '入库单号', sort: true},
            {field: 'clientProductNo', width: 120, title: '客户货号', sort: true},
            {field: 'color', width: 120, title: '颜色', sort: true},
            {field: 'productCname', width: 120, title: '中文名称', sort: true},
            {field: 'productEname', width: 120, title: '英文名称', sort: true},
            {field: 'productCdesc', width: 120, title: '中文描述', sort: true},
            {field: 'productEdesc', width: 120, title: '英文描述', sort: true},
            {field: 'specificationExplanation', width: 120, title: '规格说明', sort: true},
            {field: 'memo', title: '备注', width: 210, sort: true},
            {fixed: 'right', title: '操作', width: 110, align: 'center', toolbar: '#storageproductseditor'}]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            hoverOpenImg();//显示大图
        }
    }).config.cols;
    let aopTable = tableEdit.aopObj(cols); //获取一个aop对象
    aopTable.on('tool(storageproductstable)', function (obj) {
        let field = $(this).data('field');
        if (field === 'outStockQuantity') {
            if(obj.value > obj.data.canApplyQuantity){
                layer.msg("出库数量不能大于库存剩余数量", {icon: 5});
                return;
            }
            obj.update({"outStockQuantity": obj.value});
            layer.msg("修改成功", {icon: 6});
        }
        if (obj.event === 'del') {
            layer.confirm('确认删除?', confirmInfo(3, 5), function (index) {
                let oldData =  table.cache["storageproductstableid"];
                for (var i = 0; i < oldData.length; i++) {
                    if (oldData[i].stockId == obj.data.stockId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        switch (obj.event) {
            case 'inventoryproducts':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/WarehouseManagement/tpl/inventoryproducts.jsp'
                });
                break;
        };
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }


    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //时间处理 初始赋值
    function getNowFormatDate() {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }
    let currentDate = getNowFormatDate();
    //出库日期
    laydate.render({
        elem: '#outStockDate',
        value: currentDate,
        isInitValue: true
    });

    //创建时间
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }
})